package edu.neu.cs6515.player;

import java.util.List;

import edu.neu.cs6515.player.strategy.AbstractStrategy;
import edu.neu.cs6515.player.strategy.StrategyException;
import edu.neu.cs6515.turn.ITurnProxy;
import edu.neu.cs6515.xml.Placement;
import edu.neu.cs6515.xml.Score;
import edu.neu.cs6515.xml.Tile;

/**
 * Player represents simple player that strictly executes the required number of
 * moves that are given by the strategy
 * 
 */
public class Player extends AbstractStrategyPlayer {

    /**
     * Constructor of Player, which is a function of a IStrategy
     * 
     * @param playersName
     *            name of the player
     * 
     * @param strategy
     *            game strategy of the Player
     */
    public Player(final String playersName, final AbstractStrategy strategy) {
        super(playersName, strategy);
    }

    @Override
    public void makeYourTurn(final ITurnProxy turnproxy) {
        while (turnproxy.getRequiredPlacements() > 0) {
            Score scoreBeforePlacement = turnproxy.getCurrentScore();
            Placement placement = strategy.getNextMove(tilesInHand,
                    numberOfPlayers, turnproxy.getAllPlacementsOnBoard(),
                    scoreBeforePlacement);
            executePlacement(turnproxy, placement);
        }
        if (turnproxy.isReRackable()) {
            turnproxy.reRack();
            this.tilesInHand = turnproxy.getAllTilesInPlayersHand();
        }
    }

    /**
     * Executes one placement, if there are errors in the placement, throws
     * exception
     * 
     * @param turnproxy
     *            Proxy to be used for placement on board
     * @param placement
     *            placement to be excuted
     */
    private void executePlacement(final ITurnProxy turnproxy,
            final Placement placement) {
        List<Tile> newTile = turnproxy.placeTile(placement);
        if (!newTile.isEmpty()) {
            tilesInHand = turnproxy.getAllTilesInPlayersHand();
        }
    }

}
